<?php
/**
 * Cache
 * 
 * 作者:  姚刚 (yaogang@the9sense.com)
 * 创建时间: 2011-02-24 00:19:12
 * 修改记录: 易国磐
 * 
 * $Id: Cache.php 12 2011-03-22 06:58:27Z yiguopan2 $
 
 根据第一个参数确定要什么类型的缓存资源处理类
 第二个参数用于连接相关的资源的配置
 $cache = new Cache();
 $obj = $cache->create($alias);
 $data = $obj->get();
 */

class Cache {
	private static $backend	 = array();
	private $connections = array();

	/** 
	 * 请求相关的接口完成资源获取
	 * 
	 * @param $method 方法名称
	 * @param $params 方法对应的参数
	 * @return mix
	 */
	public function __call($method, $params) {
		if (empty($this->connections)) {
			throw new Cache_Exception('no resource connections!');
		}
		foreach($this->connections as $obj) {
			$return = @call_user_func_array(array($obj, $method), $params);
			if($method == 'get' && $return) {
				return $return;
			}
		}
		return $return;
    }

	/** 
	 * 创建资源连接，按照配置情况进行出创建
	 * 
	 * @param $alias 资源名称
	 * @return object
	 */
	public function create($alias) {
		$conf = Config::get('cache'.$alias);
		if (empty($conf)) {
			throw new Cache_Exception('please set cache config data!');
		}

		foreach ($conf as $att) {
			$obj = & Cache::factory($att['backend']);
			$connection = $obj->connect($att['conf']);
			$this->connections[$alias] = $connection;
		}
		return $this;
	}

	/**
	 * 获取CACHE单例句柄
	 *
	 * @param void
	 * @return object
	 */
	public static function &factory($cacheid) {
		if (self::$backend[$cacheid]) {
			return self::$backend[$cacheid];
		}
		
		$className = "Cache_Backend_$cacheid";
		if (!class_exists($className)) {
			throw new Cache_Exception("Cannot find '{$className}' cache file!");
		}

		$class = new $className();
		if ($class instanceof Cache_Backend_Abstract) {
			self::$backend[$cacheid] = $class;
			return $class;
		} else {
			throw new Cache_Exception("Cache class is not extends of Cache_Backend_Abstract");
		}
	}
}
